package com.jz.netthings.engine.service.impl;

import com.jy.faceValidate.utils.FaceValidateUtils;
import com.jz.netthings.appengine.baseData.ProviderInfo;
import com.jz.netthings.appengine.mapper.ProviderInfoMapper;
import com.jz.netthings.appengine.queue.ChairMgr;
import com.jz.netthings.appengine.queue.MachineMgr;
import com.jz.netthings.appengine.support.SendMsgSupport;
import com.jz.netthings.engine.service.ClientService;
import com.jz.netthings.engine.service.ZxdcChairService;
import com.jz.netthings.exception.AdscmSystemException;
import com.jz.netthings.netty.protocol.bean.ZxdcMsgPacket;
import com.jz.netthings.netty.utils.NettyMsgHelper;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ZxdcChairServiceImpl implements ZxdcChairService {

    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    ClientService clientService;
    @Autowired
    ProviderInfoMapper providerInfoMapper;


    @Override
    public ZxdcMsgPacket handleChairPacket(ZxdcMsgPacket packet) {
        ZxdcMsgPacket targetPacket = null;

        if ("faceRecognition".equals(packet.getCmd())){
            //人脸检测
            targetPacket = this.doFaceRecognition(packet);
        }else if ("authentication_donor".equals(packet.getCmd())) {
            targetPacket = this.doAuthenticationDonor(packet);
            this.doAuthPass(packet);
//            try {
//                Thread.sleep(500);
//                SendMsgSupport.revAuthToChair(packet.getCtx());
//            }catch (Exception e){}
        }else if ("auth_pass".equals(packet.getCmd())) {
//            targetPacket = this.doAuthPass(packet);
            System.out.println("auth_pass=auth_pass=auth_pass=auth_pass=auth_pass=auth_pass");
        }

        return targetPacket;
    }

    /**
     * 认证通过
     * @param packet
     * @return
     */
    private ZxdcMsgPacket doAuthPass(ZxdcMsgPacket packet){
        ZxdcMsgPacket targetPacket = null;

        String result = "failure";
        HashMap<String, Object> values = packet.getValues();
        Object donorId = values.get("donorId");
        if (donorId instanceof String) {
            ProviderInfo providerInfo = new ProviderInfo();
            providerInfo.setCardId(donorId.toString());
            providerInfo = providerInfoMapper.selectOne(providerInfo);
            if (providerInfo != null && providerInfo.getId() > 0){

                try{
                    String mac = ChairMgr.getInstance().getMacByChairCtx(packet.getCtx());
                    String chair = ChairMgr.getInstance().getChairByChairCtx(packet.getCtx());
                    ChannelHandlerContext macCtx = MachineMgr.getInstance().getMacCtx(mac);

                    logger.info(chair + " 认证通过:" + donorId.toString());


                    if (macCtx != null){
                        SendMsgSupport.auth_result(macCtx,providerInfo);
                        Map<ChannelHandlerContext, ChannelHandlerContext> chairMacMap = NettyMsgHelper.getChairMacMap();
                        chairMacMap.put(macCtx,packet.getCtx());
                        SendMsgSupport.revAuthToChair(packet.getCtx());
                    }
                    result = "success";
                }catch (Exception e){
                    logger.error("认证通过 异常",e);
                }
            }


        }
        if (packet.isHasResponse()){
            targetPacket = new ZxdcMsgPacket();
            targetPacket.setSeq(packet.getSeq());
            targetPacket.setCmd("response");
            targetPacket.setResponseFromCmd(packet.getCmd());
            values = new HashMap<String, Object>();
            values.put("result", result);
            targetPacket.setValues(values);
        }
        return targetPacket;
    }
    /**
     * 认证献浆员
     * @param packet
     * @return
     */
    private ZxdcMsgPacket doAuthenticationDonor(ZxdcMsgPacket packet){
        ZxdcMsgPacket targetPacket = null;

        String result = "failure";
        HashMap<String, Object> values = packet.getValues();
        Object deviceId = values.get("deviceId");
        if (deviceId instanceof String) {
            Object donorId = values.get("donorId");
            if (donorId instanceof String) {
                logger.info(deviceId.toString() + " 认证献浆员:" + donorId.toString());
                String mac = ChairMgr.getInstance().getMacByChair(deviceId.toString());
                ChannelHandlerContext macCtx = MachineMgr.getInstance().getMacCtx(mac);

                if (macCtx != null){

                    ProviderInfo providerInfo = new ProviderInfo();
                    providerInfo.setCardId(donorId.toString());
                    providerInfo = providerInfoMapper.selectOne(providerInfo);
                    if (providerInfo != null && providerInfo.getId() > 0){
                        SendMsgSupport.auth_pass(macCtx,providerInfo);
                        result = "success";
                    }
                }

            }
        }
        if (packet.isHasResponse()){
            targetPacket = new ZxdcMsgPacket();
            targetPacket.setSeq(packet.getSeq());
            targetPacket.setCmd("response");
            targetPacket.setResponseFromCmd(packet.getCmd());
            values = new HashMap<String, Object>();
            values.put("result", result);
            targetPacket.setValues(values);
        }
        return targetPacket;
    }

    /**
     * 人脸检测
     * @param packet
     * @return
     */
    private ZxdcMsgPacket doFaceRecognition(ZxdcMsgPacket packet) {
        ZxdcMsgPacket targetPacket = new ZxdcMsgPacket();

        HashMap<String, Object> values = packet.getValues();
        Object donorId = values.get("donorId");
        Object face = values.get("face");

        if (donorId instanceof String){
            if (face instanceof byte[]){
                targetPacket = EngineSupport.faceRecognition((String) donorId, (byte[])face,packet.getSeq(),packet.getCmd(),clientService,logger);
            }
        }
        return targetPacket;
    }

}
